package com.heima.wemedia.filter;


import com.heima.wemedia.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class AuthorizeFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String reqUrl = request.getURI().getPath();
        if(reqUrl.contains("/login/in")){
           return chain.filter(exchange);
        }
        String jwtToken = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(jwtToken)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
        Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
        int verifyToken= AppJwtUtil.verifyToken(claims);
        if(verifyToken>0){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Integer id= claims.get("id", Integer.class);
        //log.info("header token id:{}, URL:{}", id, request.getURI().getPath());
        //mutate()方法是：如果有多个控件或是界面同时引用某一个资源，并且要改变该资源的状态时就需要用mutate方法。使用mutate是为了更改一个资源的状态时，其余引用该资源的控件不会也更改状态。
        request.mutate().headers(httpHeaders -> {
            httpHeaders.add("userId",String.valueOf(id));
        }).build();
        }catch (Exception e){
            e.printStackTrace();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
